package com.danco.training.zaneuskaya.repository.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;






import com.danco.training.zaneuskaya.repository.GenericDao;
/**
 * @author Zaneuskaya Aliaksandra
 *
 */
@Repository
public abstract class AbstractHibernateDao<T, PK extends Serializable>
		implements GenericDao<T, PK> {
	
	@Autowired
	private SessionFactory sessionFactory;
		
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}


	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}


	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}


	public void create(T object) throws HibernateException {
		getSession().persist(object);

	}

	
	
	@SuppressWarnings("unchecked")
	public T read( Class<T> cl, Integer PK)
			throws HibernateException {
		return   (T) getSession().get(cl, PK);

	}

	@SuppressWarnings("unchecked")
	public List<T> readAll(Class<T> cl, String column) throws HibernateException {
		List<T> entities = new ArrayList<T>();
		entities =  modifyCriteria(getSession().createCriteria(cl), column).list();
		return entities;
	}

	public void update(T object) throws HibernateException {
		getSession().merge(object);
	}

	
	public void delete(T object) throws HibernateException {
		getSession().delete(object);

	}
	
	public Criteria modifyCriteria(Criteria criteria, String column) throws HibernateException {
		if(!column.isEmpty()){
		criteria.addOrder(Order.asc(column));
		}
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return criteria;
	}

}
